<template>
  <div class="department-container">
    <div class="app-container">
      <!-- 具体页面结构 -->
      <page-tools>
        <!-- 插入到left插槽位置 -->
        <template #left>
          <span>总记录数: {{ total }}条</span>
        </template>
        <!-- 插入到right插槽位置 -->
        <template #right>
          <el-button v-allow="'import_excel'" type="warning" size="small" @click="$router.push('/import')">导入excel</el-button>
          <el-button v-allow="'export_excel'" type="danger" size="small" @click="hExportExcel">导出excel</el-button>
          <el-button v-allow="'add_employees'" type="primary" size="small" @click="hAdd">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 表格区域 -->
      <el-card style="margin-top: 10px;">
        <el-table
          border
          :data="list"
          :default-sort="{ prop: 'timeOfEntry', order: 'descending' }"
        >
          <el-table-column label="序号" type="index" :index="updateIndex" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="工号" prop="workNumber" sortable />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{row}">
              {{ formOfEmploymentFormat(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable>
            <template #default="{row}">
              {{ dataFormDate(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail?id=${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="hRole(row.id)">分配角色</el-button>
              <el-button v-allow="'delete'" type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <paGing
          :total="total"
          :page-params="pageParams"
          @setSizeChange="handleSizeChange"
          @setCurrentChange="handleCurrentChange"
        />
      </el-card>
      <el-dialog
        title="新增员工"
        :visible.sync="showDialog"
        @closed="hClose"
      >
        <emp-dialog
          ref="empDiaglogRefs"
          :work-number-list="workNumberList"
          @close="showDialog=false"
          @addNewUser="updateUser"
        />
      </el-dialog>
      <!-- 分配角色 -->
      <el-dialog
        :visible.sync="showDialogRole"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        title="分配角色"
      >
        <assign-role
          ref="assignRole"
          :employe-id="curEmployeId"
          @close="close"
        />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import AssignRole from './assignRole.vue'
import employeesEnum from '@/constant/employees.js'
import { getEmploye, delEmployee } from '@/api/employee'
import dayjs from 'dayjs'
import empDialog from './empDialog.vue'
console.log(employeesEnum.hireType) // [{id: 1, value: '正式'},{id: 1, value: '正式'}]
// const hireType = {}
// employeesEnum.hireType.forEach(item => { hireType[item.id] = item.value })
const hireType = employeesEnum.hireType.reduce((acc, item) => ({ ...acc, [item.id]: item.value }), {})
console.log(hireType)
export default {
  components: { empDialog, AssignRole },
  data() {
    return {
      // 员工列表数据
      list: [],
      // 员工工号
      workNumberList: [],
      curEmployeId: '', // 当前员工的编号
      // 总列表数
      total: 0,
      pageParams: {
        page: 1, // 页码
        size: 5 // 每页数据
      },
      // 控制对话框打开关闭
      showDialog: false,
      // 角色分配控制显示隐藏
      showDialogRole: false
    }
  },
  created() {
    // 获取员工列表
    this.loadEmployeeList()
  },
  methods: {
    close() {
      this.showDialogRole = false
      this.loadEmployeeList()
    },
    // 格式化时间
    dataFormDate(time) {
      return dayjs(time).format('YYYY-MM-DD')
    },
    // 将1,2转换为正式,非正式
    formOfEmploymentFormat(id) {
      return hireType[id]
    },
    // 更新序列号
    updateIndex(index) {
      return index + this.pageParams.size * (this.pageParams.page - 1) + 1
    },
    // 更新当前页数据量
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.pageParams.size = val
      this.pageParams.page = 1
      // 更新数据
      this.loadEmployeeList()
    },
    // 更新当前页码
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.pageParams.page = val
      // 更新数据
      this.loadEmployeeList()
    },
    // 获取员工列表
    async  loadEmployeeList() {
      try {
        const res = await getEmploye(this.pageParams)
        console.log(res)
        this.list = res.data.rows
        this.total = res.data.total
        this.workNumberList = res.data.rows.reduce((acc, item) => ([...acc, item.workNumber]), [])
        console.log(this.workNumberList)
      } catch (err) {
        console.log(err)
      }
    },
    // 删除员工
    async doDel(id) {
      try {
        await delEmployee(id)
        if (this.list.length === 1) {
          this.page--
          if (this.page <= 0) {
            this.page = 1
          }
        }
        this.loadEmployeeList()
      } catch (err) {
        console.log(err)
      }
    },
    // 根据id删除用户
    hDel(id) {
      this.$confirm('此操作将永久删除该员工, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.doDel(id)
      }).catch(() => {
        // 取消
      })
    },

    // 新增员工
    hAdd() {
      this.showDialog = true
    },
    // 关闭对话框
    hClose() {
      this.$refs.empDiaglogRefs.resetForm()
    },
    // 接收子组件新增员工消息,刷新页面
    updateUser() {
      // 添加成功，进入最后一页看数据
      this.total++
      // 最后一页
      this.pageParams.page = Math.ceil(this.total / this.pageParams.size)
      // 刷新页面
      this.loadEmployeeList()
      // 关闭对话框
      this.showDialog = false
      console.log(1)
    },
    formatData(list) {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      let header = []// 表头
      let data = [] // 存储数据值
      const one = list[0]
      if (!one) {
        return { header, data }
      }
      header = Object.keys(one).map(key => mapInfo[key])

      data = list.map(obj => {
        obj.formOfEmployment = hireType[obj.formOfEmployment] // 转换正式非正式
        return Object.values(obj)
      })
      return { header, data }
    },
    // 导出excel
    async hExportExcel() {
      // 1. 发请求拿到真实的数据
      try {
        const res = await getEmploye(this.pageParams)
        const excelList = res.data.rows
        // 2. 将拿到的数据进行格式化操作
        const { header, data } = this.formatData(excelList)
        console.log({ header, data })
        // 3. 将格式化之后的数据转换成excel表格
        import('@/vendor/Export2Excel').then(excel => {
          // excel表示导入的模块对象
          console.log(excel)
          excel.export_json_to_excel({
            header, // 表头
            data, // 具体数据
            filename: 'hr-excel-list', // 文件名称
            autoWidth: true, // 宽度是否自适应
            bookType: 'xlsx' // 生成的文件类型
          })
        })
      } catch (err) {
        console.log(err)
      }
    },
    // 用户点击分配角色
    hRole(id) {
      this.showDialogRole = true
      this.curEmployeId = id
      this.$nextTick(() => {
        this.$refs.assignRole.loadRoles()
      })
    }
  }
}

</script>
